'use strict';

const BaseService = require('./base');
const modelName = 'User';
const wxConfig = require("../../config/wx");
const WXBizDataCrypt = require('../../config/WXBizDataCrypt');
class RouterService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }
  // 微信授权一键登录
  async wxLogin(data) {
    const { code, encryptedData, iv } = data;
    try {
      const { openid, session_key } = await this.exchangeCodeForSessionKey(code)
      const phone = this.decryptPhoneNumber(session_key, encryptedData, iv)
      return await this.loginForm(openid, phone)
    } catch (error) {
      console.log(error)
      throw new Error(error);
    }
  }

  async loginForm(openid, phone) {
    const { User } = this.ctx.model;
    // 根据手机号查询用户是否存在
    let user = await User.findOne({
      where: {
        openid,
        phone
      },
    });
    if (!user) {
      // 去注册
      let createUser = await User.create({
        password: '123456',
        openid,
        phone,
        nickname: '用户' + new Date().getTime(),
        avatar_url: '/static/images/user.png'
      })
      let userValue = createUser.dataValues;
      delete userValue.password;
      return userValue;
    } else {
      return user.dataValues
    }
  }

  async exchangeCodeForSessionKey(code) {
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxConfig.appid}&secret=${wxConfig.secret}&js_code=${code}&grant_type=authorization_code`;
    const response = await this.ctx.curl(url, { dataType: 'json' });
    const data = response.data;
    if (!data.session_key || !data.openid) {
      throw new Error('Failed to exchange code for session_key and openid');
    }
    return {
      session_key: data.session_key,
      openid: data.openid,
    };
  }
  decryptPhoneNumber(session_key, encryptedData, iv) {
    const pc = new WXBizDataCrypt(wxConfig.appid, session_key);
    const data = {};
    const errCode = pc.decryptData(encryptedData, iv, data);
    return errCode.phoneNumber
  }


  // 注册，判断手机号是否存在
  async register(data) {
    const { User } = this.ctx.model;
    const { phone } = data;
    let user = await User.findOne({
      where: {
        phone
      },
    });
    if (user) {
      throw new Error('手机号已注册');
    } else {
      const res = await User.create(data);
      // 超找信息
      return await this.findOne(res.id)
    }
  }
  // 登录验证密码
  async login(data) {
    const { User } = this.ctx.model;
    const { phone, password } = data;
    let user = await User.findOne({
      where: {
        phone,
        password
      },
    });
    if (!user) {
      throw new Error('手机号或密码错误');
    } else {
      if (!user.status) {
        throw new Error('用户已禁用');}
      }
      return await this.findOne(user.id)
    }
}


module.exports = RouterService;
